# task_master.py
import datetime
from multiprocessing import Queue
from multiprocessing.managers import BaseManager

# 从BaseManager继承的QueueManager:
import facade
from xjlibrary.network.MyIP import GetLocalIPByPrefix
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")


class QueueManager(BaseManager):
    pass


class SendTask(object):
    def __init__(self):
        # 发送任务的队列:
        self.task_queue = Queue()
        # 接收结果的队列:
        self.result_queue = Queue()
        self.register()
        self.ip = GetLocalIPByPrefix("192.168.")
        # 绑定端口5000, 设置验证码'abc':
        self.manager = QueueManager(address=(self.ip, 5000), authkey=b'abc')
        self.task = None
        self.result = None

    def register(self):
        # 把两个Queue都注册到网络上, callable参数关联了Queue对象:
        QueueManager.register('get_task_queue', callable=self.return_task_queue)
        QueueManager.register('get_result_queue', callable=self.return_result_queue)

    def return_task_queue(self):
        return self.task_queue

    def return_result_queue(self):
        return self.result_queue

    def start(self):
        # 启动Queue:
        self.manager.start()

    def set_task_result_obj(self):
        # 获得通过网络访问的Queue对象:
        self.task = self.manager.get_task_queue()
        self.result = self.manager.get_result_queue()

    def set_task(self, n):
        print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
        print(n)
        self.task.put(n)

    def get_result(self):
        # 从result队列读取结果:
        # print('Try get results...')
        # try:
        #     for i in range(10):
        #         r = self.result.get(timeout=10)
        #         print('Result: %s' % r)
        # except queue.Empty:
        #     print('task queue is empty.')
        pass

    def shutdown(self):
        # 关闭:
        self.manager.shutdown()
        print('master exit.')


class SelectTask(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile,
                                             "db",
                                             logger=self.logger)

    def selectDB(self):
        sql = "select standardid from articlenew where stat=0 and failcount<3 limit 1000"
        # sql = "select wanID from article1 where stat=0 and failcount <3 limit 50000"
        rows = self.mysqlutils.SelectFromDB(sql)
        return rows


if __name__ == "__main__":
    sendtask = SendTask()
    select = SelectTask()
    sendtask.start()
    sendtask.set_task_result_obj()
    while True:
        if sendtask.task.qsize() != 0:
            print("send task num is:"+str(sendtask.task.qsize()))
        else:
            rows = select.selectDB()
            if rows:
                for row in rows:
                    sendtask.set_task(row[0])

        if sendtask.result.qsize() != 0:
            print("result num is:"+str(sendtask.result.qsize()))
            truelist = []
            falselist=[]
            for i in range(1, sendtask.result.qsize()+1):
                result = sendtask.result.get()
                if result[1] == 1:
                    truelist.append(result[0])
                else:
                    falselist.append(result[0])
            if truelist:
                if len(truelist) == 1:
                    truelist.append("test")
                sql = "update articlenew set stat=1 where standardid in {}".format(tuple(truelist))
                # sql = "update article1 set stat=1 where wanID in {}".format(tuple(truelist))
                select.mysqlutils.ExeSqlToDB(sql)
            if falselist:
                if len(falselist) == 1:
                    falselist.append("test")
                sql = "update articlenew set failcount=failcount+1 where standardid in {}".format(tuple(falselist))
                # sql = "update article1 set failcount=failcount+1 where wanID in {}".format(tuple(falselist))
                select.mysqlutils.ExeSqlToDB(sql)

